package org.thanos.demo.config;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thanos.demo.entity.LogEvent;
import org.thanos.demo.entity.LogEventFactory;
import org.thanos.demo.consumer.LogEventConsumer;
import org.thanos.demo.producer.LogEventProducer;

@Configuration
public class DisruptorConfig {

    @Autowired
    private LogEventConsumer logEventConsumer;

    @Bean(name = "disruptor")
    public Disruptor<LogEvent<String>> disruptor() {
        LogEventFactory<String> factory = new LogEventFactory<String>();
        int ringBufferSize = 1024;
        Disruptor<LogEvent<String>> disruptor = new Disruptor<>(factory, ringBufferSize, DaemonThreadFactory.INSTANCE);
        disruptor.handleEventsWith(logEventConsumer);
        disruptor.start();
        return disruptor;
    }

    @Bean(name = "logEventProducer")
    public LogEventProducer logEventProducer() {
        RingBuffer<LogEvent<String>> ringBuffer = disruptor().getRingBuffer();
        return new LogEventProducer(ringBuffer);
    }
}
